package com.pn.service.impl;


import com.pn.entity.Result;
import com.pn.entity.Role;
import com.pn.mapper.RoleAuthMapper;
import com.pn.mapper.RoleMapper;
import com.pn.page.Page;
import com.pn.service.RoleAuthService;
import com.pn.service.RoleService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@CacheConfig(cacheNames = "com.pn.service.impl.RoleServiceImpl")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleAuthMapper roleAuthMapper;

    @Cacheable(key = "'all:role'")
    @Override
    public List<Role> findAllRole(){
        return roleMapper.selectAllRole();
    }


    @Override
    public Page queryRoleByPage(Role role,Page page) {
        int roleCount = roleMapper.findRoleCount(role);
        List<Role> roles = roleMapper.selectRoleByPage(role,page);
        page.setTotalNum(roleCount);
        page.setResultList(roles);
        return page;
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public Result addRole(Role role) {
        List<Role> roles = roleMapper.selectRoleIsExist(role);
        if (roles.size() == 0){
            int i = roleMapper.insertNewRole(role);
            if (i != 0){
                return Result.ok("角色添加成功！");
            }else {
                return Result.err(Result.CODE_ERR_SYS,"角色添加失败！");
            }
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS,"角色信息已存在！");
        }

    }

    @CacheEvict(key = "'all:role'")
    @Override
    public int modifyRoleState(Role role) {
        int i = roleMapper.updateRoleState(role);
        return i;
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public int deleteRole(Integer roleId) {
        roleAuthMapper.deleteRoleAuthByRid(roleId);
        return roleMapper.deleteRole(roleId);
    }

    @CacheEvict(key = "'all:role'")
    @Override
    public int modifyRoleDescByRid(Role role,Integer updateBy) {
        return roleMapper.updateRoleDescByRid(role.getRoleDesc(),role.getRoleId(),updateBy);
    }


}
